package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    //  api/order/auth/trade    网关中设置了访问这个路径必须登录！
    @GetMapping("auth/trade")
    public Result authTrade(HttpServletRequest request) {
        //往前端页面传送数据
        HashMap<String, Object> hashMap = new HashMap<>();
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //获取送货地址列表
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        //获取送货清单
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);

        //  循环遍历给订单明细赋值！
        //  计算件数：
        AtomicInteger totalNum = new AtomicInteger();
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setOrderPrice(this.productFeignClient.getSkuPrice(orderDetail.getSkuId()));
            totalNum.addAndGet(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());

        //  计算总价格：
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount();
        //  存储数据：
        hashMap.put("userAddressList",userAddressList);
        //  订单业务需要换---> 缓存没有优惠券的页面！
        hashMap.put("detailArrayList",orderDetailList);
        //  两种：一种：计算集合的长度  集合长度 ：size(); 数组长度 length; 字符串：length(); 文件长度：length();
        //  一种：计算每个商品的skuNum
//        hashMap.put("totalNum",orderDetailList.size());
        hashMap.put("totalNum",totalNum);
        hashMap.put("totalAmount",orderInfo.getTotalAmount());
        //  保存一个流水号：
        hashMap.put("tradeNo",orderService.getTradeNo(userId));

        return Result.ok(hashMap);
    }

    //  提交订单：http://api.gmall.com/api/order/auth/submitOrder?tradeNo=null
    //  前端传递的json ，后端需要使用java 对象接收！
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //获取到页面的流水号
        String tradeNo = request.getParameter("tradeNo");
        //  调用比较方法
        Boolean result = orderService.checkTradeNo(tradeNo, userId);
        //        if (result){
        //            //  true: 成功
        //        }else {
        //            //  false: 不能成功！
        //        }
        if (!result){
            return Result.fail().message("不能回退无刷新重复提交订单！");
        }
        //  删除缓存的流水号！
        orderService.delTradeNo(userId);

        /*List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //验证库存
        for (OrderDetail orderDetail : orderDetailList) {
            Boolean res = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
            //  校验库存！
            if (!res) {
                return Result.fail().message(orderDetail.getSkuName() + "没有足够的库存！");
            }
            //  校验价格：
            BigDecimal orderPrice = orderDetail.getOrderPrice();
            //  实时价格：
            BigDecimal skuPrice = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
            if (orderPrice.compareTo(skuPrice) != 0) {
                //  设置最新的价格
                List<CartInfo> cartCheckedList = this.cartFeignClient.getCartCheckedList(userId);
                //  写入缓存：
                cartCheckedList.forEach(cartInfo -> {
                    this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                });
                return Result.fail().message(orderDetail.getSkuName() + "价格有变动！");
            }
        }
*/
//  声明一个异步编排集合
        List<String> errorList = new ArrayList<>();
        List<CompletableFuture> futureList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            //  循环遍历当前的订单明细
            for (OrderDetail orderDetail : orderDetailList) {
                //  验证库存
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    Boolean res = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    //  校验库存！
                    if (!res) {
                        errorList.add(orderDetail.getSkuName() + "没有足够的库存！");
                    }
                }, threadPoolExecutor);
                //  将这个对象添加到集合！
                futureList.add(stockCompletableFuture);
                //  验证价格
                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  校验价格：
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    //  实时价格：
                    BigDecimal skuPrice = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderPrice.compareTo(skuPrice) != 0) {
                        //  设置最新的价格
                        List<CartInfo> cartCheckedList = this.cartFeignClient.getCartCheckedList(userId);
                        //  写入缓存：
                        cartCheckedList.forEach(cartInfo -> {
                            this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                        });
                        errorList.add(orderDetail.getSkuName() + "价格有变动！");
                    }
                },threadPoolExecutor);
                //  将这个对象添加到集合！
                futureList.add(priceCompletableFuture);
            }
        }

        //  有个任务组合
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        //  判断是否有错误：
        if (errorList.size()>0){
            return Result.fail().message(StringUtils.join(errorList,","));
        }
        orderInfo.setUserId(Long.parseLong(userId));
        //  调用服务层方法
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //  默认返回
        return Result.ok(orderId);
    }

    //  查看我的订单
    @GetMapping("auth/{page}/{limit}")
    public Result orderList(@PathVariable Long page,
                            @PathVariable Long limit,
                            HttpServletRequest request){
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //分页信息
        Page<OrderInfo> orderInfoPage = new Page<>(page, limit);
        //  获取到数据
        IPage<OrderInfo> infoIPage = orderService.getPage(orderInfoPage, userId);

        //  返回
        return Result.ok(infoIPage);
    }
}